﻿Imports System.Data.SqlServerCe

Public Class TransactionScope
    Implements IDisposable

    Private mConnection As SqlCeConnection
    Private mTransaction As SqlCeTransaction
    Private mDataSource As DataSource

    ''' <summary>
    ''' Default datasource is Local
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub New()
    End Sub
    ''' <summary>
    ''' Set explicit datasource
    ''' </summary>
    ''' <param name="dataSource"></param>
    ''' <remarks></remarks>
    Public Sub New(ByVal dataSource As DataSource)
        mDataSource = dataSource
    End Sub

    Public ReadOnly Property Connection() As SqlCeConnection
        Get
            If mConnection Is Nothing Then
                mConnection = Environment.GetConnection(mDataSource)
                mConnection.Open()
            End If
            Return mConnection
        End Get
    End Property
    Public ReadOnly Property Transaction() As SqlCeTransaction
        Get
            If mTransaction Is Nothing Then
                mTransaction = mConnection.BeginTransaction(IsolationLevel.Serializable)
            End If
            Return mTransaction
        End Get
    End Property


    Public Sub Complete()
        If mTransaction IsNot Nothing Then
            mTransaction.Commit(CommitMode.Immediate)
            mTransaction = Nothing
        End If
        If mConnection IsNot Nothing Then
            mConnection.Close()
            mConnection = Nothing
        End If
    End Sub

    Private disposedValue As Boolean = False        ' To detect redundant calls

    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                ' TODO: free other state (managed objects).
            End If

            If mTransaction IsNot Nothing Then
                mTransaction.Rollback()
                mTransaction = Nothing
            End If
            If mConnection IsNot Nothing Then
                mConnection.Close()
                mConnection = Nothing
            End If
        End If
        Me.disposedValue = True
    End Sub

#Region " IDisposable Support "
    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

End Class
